var Tasklog=Tasklog||{}
Tasklog.DB = (function(Tasklog){ return {
	statusTimeout:{}, db:null

	,init: function(){
		var taskConf={ tableName: 'task', tableSql:'create table task (id integer primary key asc, priority mediumint not null, description text not null, status tinyint(1) not null default 0, tags varchar(255) not null default "")' }
		var tagConf={ tableName: 'tag', tableSql:'create table tag (id integer primary key asc, name varchar(25) not null, color varchar(25) default "#ffffff", bg varchar(25) default "#333333")' }
		this.db=DATABASE; // gears or air depending on the js included
		this.db.dbInit('tasklog');
		this.db.tableInit(taskConf);
		this.db.tableInit(tagConf);
	}
	
	
//*** TASKS ***	
	,updateStatus: function(){ // shows the "saved" info
		try{clearTimeout(this.statusTimeout)}catch(e){}
		var sS=$('#saveStatus');
		sS.css({opacity:1, display:'' });
		sS.text('Saved @ '+new Date().format('HH:MM:ss'));
		this.statusTimeout=setTimeout(function(){sS.fadeOut()},2000)
	}

	,getTasks: function(completed){
		if (completed) return this.db.dbTable('SELECT * FROM task WHERE status=1 ORDER BY priority');
		else return this.db.dbTable('SELECT * FROM task WHERE status=0 ORDER BY priority');
	}

	,getAll: function(){ return this.db.getAll('task','priority') }

	,getTaskById: function(id){ return this.db.getByID('task',id) }

	,del: function(id){
		var task=this.db.getByID('task',id);
		if (task) this.db.dbEdit('update task set priority=priority-1 where priority>?', [task.priority]) // move all tasks below -1
		var success=this.db.delData('task',id)
		if (success) this.updateStatus();
		return true;
	}
	
	,add: function(rec){
		if (rec.priority) this.db.dbEdit('update task set priority=priority+1 where priority>=?', [rec.priority]) // move all tasks below +1
		var newID=this.db.addData('task', rec);
		if (!newID) return false;
		this.updateStatus();
		return newID;
	}
	
	,update: function(id, rec){
		if (rec.description==undefined) delete(rec.description);
		if (typeof rec.status!='number') delete(rec.status);
		var updID=this.db.editData('task', rec, id);
		if (updID) this.updateStatus();
		return true;
	}
	
	,updateDD: function(tId, nId){  // update after reorder thisId, nextId
		var tTask, nTask, tPr=0, nPr=0, rowsA=0;
		tTask=this.db.getByID('task',tId); 
		tPr=tTask.priority;
		if (nId=='last'){
			rowsA=this.db.dbEdit('update task set priority=priority-1 where priority>?', [ tPr ]); //move task to the bottom down
			this.db.dbEdit('update task set priority=priority+? where id=?', [ rowsA, tId ]);
		}
		else{
			nTask=this.db.getByID('task',nId); 
			nPr=nTask.priority;
			if (Math.abs(tPr-nPr)==1){ // if move row up/down
				this.db.dbEdit('update task set priority=? where id=?', [ nPr, tId ]);
				this.db.dbEdit('update task set priority=? where id=?', [ tPr, nId ]);
			}
			else {
				if (tPr<nPr) this.db.dbEdit('update task set priority=priority-1 where priority>? and priority<?', [ tPr, nPr ]); //move task down
				else this.db.dbEdit('update task set priority=priority+1 where priority<? and priority>=?', [ tPr, nPr ]); //move task up
				this.db.dbEdit('update task set priority=? where id=?', [ nPr, tId ]);
			}
		}	
		return true;
	}



//*** TAGS ***	
	,addTaskTag: function(tag,id){
		var tags, tagStr; 
		tag=tag.trim();
		tags=this.db.getByID('task',id).tags.split(','); // get task tags to array
		if(!tags.in_array(tag)) tags.push(tag);	// if tag not exists - add one
		tagStr=tags.sort().join(',');
		if (tagStr[0]==',') tagStr=tagStr.substr(1) // remove first comma if any
		this.db.dbEdit('update task set tags=? where id=?', [tagStr, id]);
	}
	
	,removeTaskTag: function(tag,id){
		var tags=this.db.getByID('task',id).tags.split(','); // get task tags to array
		tags=tags.remove(tag.trim()).sort().join(',');
		this.db.dbEdit('update task set tags=? where id=?', [tags, id]);
	}

	,addTag: function(rec){ return this.db.addData('tag', rec) }
	,updateTag: function(rec){ return this.db.editData('tag', rec, rec.id) }
	,removeTag: function(id){ return this.db.delData('tag',id) }
	,getTags: function(){ return this.db.getAll('tag','name') }
	
}})(Tasklog);